#include<iostream>
#include<cstdlib>
#include<unistd.h>
#include<strings.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<pthread.h>
#include"Terminal.hpp"

using namespace std;

void Usage(string proc)
{
    cout<<"\n\rUsage: "<<proc<<"serverip serverport\n"<<endl;
}
struct ThreadData
{
    struct sockaddr_in server;
    int sockfd;
    string serverip;
};

void* recv_message(void *args)
{
    //OpenTerminal();
    ThreadData*td=static_cast<ThreadData*>(args);
    char buffer[1024];
    while(true)
    {
        //char buffer[1024];
        memset(buffer,0,sizeof(buffer));
        struct sockaddr_in temp;//存储发送方的地址信息
        socklen_t len=sizeof(temp);
        ssize_t s=recvfrom(td->sockfd,buffer,1023,0,(struct sockaddr*)&temp,&len);
        if(s>0)
        {
            //std::cout << "s: --" << s  << "--"<< endl; 
            buffer[s]=0;
            cerr<<buffer<<endl;//cerr的无缓冲特性，确保即时显示信息
        }
    }
}
void* send_message(void*args)
{
    ThreadData*td=static_cast<ThreadData*>(args);
    string message;
    socklen_t len=sizeof(td->server);
    string welcome=td->serverip;
    welcome+=" coming...";
    //向服务器发送一条客户上线的欢迎消息
    sendto(td->sockfd,message.c_str(), message.size(),0,(struct sockaddr*)&(td->server),len);
    
    while(true)
    {
        cout<<"please enter@"  << std::endl;;
      
        getline(cin,message);//从标准输入读取用户输入的消息
        //将消息发送到服务器的地址（server结构体）
        sendto(td->sockfd,message.c_str(),message.size(),0,(struct sockaddr*)&(td->server),len);
        message.clear();
    }
}

//使用多线程同时进行读写，实现功能解耦
// ./udpclient serverip serverport总共接受三个参数
int main(int argc,char*argv[])
{
    if(argc!=3)
    {
        Usage(argv[0]);
        exit(0);
    }
    string serverip=argv[1];
    uint16_t serverport=stoi(argv[2]);

    struct ThreadData td;
    bzero(&td.server,sizeof(td.server));
    td.server.sin_family=AF_INET;
    td.server.sin_port=htons(serverport);//将主机字节序转化为网络字节序
    td.server.sin_addr.s_addr=inet_addr(serverip.c_str());//将点分十进制的 IP 字符串转换为网络字节序的整数
    socklen_t len=sizeof(td.server);
    td.sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(td.sockfd<0)
    {
        cout<<"socker error"<<endl;
        return 1;
    }

    td.serverip=serverip;

    pthread_t recvr,sender;
    pthread_create(&recvr,nullptr,recv_message,&td);
    pthread_create(&sender,nullptr,send_message,&td);

    pthread_join(recvr,nullptr);
    pthread_join(sender,nullptr);
    close(td.sockfd);
    return 0;
}